// ReportItem 类型定义
export interface DeviceInfo {
  name: string;
  value: string;
}

export interface FaultInfo {
  name: {
    "#text": string;
    "@_InfCode": string;
  };
  value:
    | {
        "#text"?: string;
        "@_InfCode"?: string;
      }
    | string;
}

export interface TripInfo {
  time: string;
  name: string;
  phase: string;
  value: string;
  FaultInfo: FaultInfo | FaultInfo[];
}

// 新增的类型定义
export interface DigitalStatusItem {
  name: string;
  value: number;
}

export interface DigitalEventItem {
  time: string;
  name: string;
  value: number;
}

export interface SysSettingValueItem {
  name: string;
  value: number | string;
  unit: string;
}

export interface SettingValueItem {
  name: string;
  value: number | string;
  unit: string;
}

export interface RelayEnaInfoItem {
  name: string;
  value: number;
}

export interface ReportItem {
  reportName: string;
  reportId: number;
  faultId: number;
  faultTime: string;
  faultStartTime: string;
  faultKeepingTime: string;
  DataFileSize: number;
  deviceInfo: DeviceInfo[];
  tripInfo: TripInfo[];
  // actionElement: {
  //   currentSpeed: string;
  //   powerSupply: string;
  // };
  // recloser: string;
  // tLineVoltage: string;
  // fLineVoltage: string;
  // tLineCurrent: string;
  // fLineCurrent: string;
  // tfCurrent: string;
  // impedance: string;
  // impedanceAngle: string;
  // resistance: string;
  // reactance: string;
  // secondHarmonic: string;
  // currentSpeedStart: string;
  // forwardCurrentSpeedStart: string;
  // busLock: string;
  // currentSpeedAction: string;
  // forwardCurrentSpeedAction: string;
  // breakerFailure: string;
  // breakerTripCircuitFailure: string;
  // viewReportValue: {
  //   tfCurrent: string;
  //   impedance: string;
  //   impedanceAngle: string;
  //   resistance: string;
  // };
  // 新增的属性
  digitalStatus: DigitalStatusItem[];
  digitalEvent: DigitalEventItem[];
  sysSettingValue: SysSettingValueItem[];
  settingValue: SettingValueItem[];
  relayEnaInfo: RelayEnaInfoItem[];
}

// @ts-expect-error: fast-xml-parser 需安装类型声明
import { XMLParser } from "fast-xml-parser";

/**
 * 解析 hdr XML 字符串为 ReportItem 对象
 * @param xmlStr hdr 文件内容
 * @param id 模拟报告ID
 */
export function parseHdrToReportItem(xmlStr: string, id: number, reportName: string): ReportItem {
  const parser = new XMLParser({ ignoreAttributes: false });
  const obj = parser.parse(xmlStr);
  const report = obj.FaultReport;

  // 设备信息映射
  const deviceInfo = Array.isArray(report.DeviceInfo) ? report.DeviceInfo : [report.DeviceInfo];

  // TripInfo 处理 - 深度解析 FaultInfo
  const tripInfo = Array.isArray(report.TripInfo) ? report.TripInfo : [report.TripInfo];

  // 深度解析每个 TripInfo 的 FaultInfo
  const processedTripInfo = tripInfo.map((trip: any) => {
    if (trip.FaultInfo) {
      // 确保 FaultInfo 是数组格式
      const faultInfos = Array.isArray(trip.FaultInfo) ? trip.FaultInfo : [trip.FaultInfo];
      return {
        ...trip,
        FaultInfo: faultInfos,
      };
    }
    return trip;
  });

  // 主报告量值（第一个 TripInfo）
  const mainTrip = processedTripInfo[0];
  const faultInfos = mainTrip?.FaultInfo || [];

  // 优化 getFaultValue 函数，支持深度解析
  const getFaultValue = (name: string) => {
    if (Array.isArray(faultInfos)) {
      const info = faultInfos.find((fi: any) => {
        const faultName = fi.name?.["#text"] || fi.name;
        return faultName === name;
      });
      return info?.value?.["#text"] || info?.value || "-";
    } else if (faultInfos.name?.["#text"] === name) {
      return faultInfos.value?.["#text"] || faultInfos.value || "-";
    }
    return "-";
  };

  // 解析新增属性
  const digitalStatus = Array.isArray(report.DigitalStatus)
    ? report.DigitalStatus
    : report.DigitalStatus
      ? [report.DigitalStatus]
      : [];

  const digitalEvent = Array.isArray(report.DigitalEvent)
    ? report.DigitalEvent
    : report.DigitalEvent
      ? [report.DigitalEvent]
      : [];

  const sysSettingValue = Array.isArray(report.SysSettingValue)
    ? report.SysSettingValue
    : report.SysSettingValue
      ? [report.SysSettingValue]
      : [];

  const settingValue = Array.isArray(report.SettingValue)
    ? report.SettingValue
    : report.SettingValue
      ? [report.SettingValue]
      : [];

  const relayEnaInfo = Array.isArray(report.RelayEnaInfo)
    ? report.RelayEnaInfo
    : report.RelayEnaInfo
      ? [report.RelayEnaInfo]
      : [];

  // 其他字段映射
  return {
    reportName,
    reportId: id,
    faultId: id,
    faultTime: report.FaultStartTime || "-",
    faultStartTime: report.FaultStartTime || "-",
    faultKeepingTime: report.FaultKeepingTime || "-",
    DataFileSize: report.DataFileSize || 0,
    deviceInfo,
    tripInfo: processedTripInfo,
    // actionElement: {
    //   currentSpeed: getFaultValue("动作元件"),
    //   powerSupply: getFaultValue("电流速断,供电臂保护"),
    // },
    // recloser: getFaultValue("重合闸"),
    // tLineVoltage: getFaultValue("T线保护电压"),
    // fLineVoltage: getFaultValue("F线保护电压"),
    // tLineCurrent: getFaultValue("T线保护电流"),
    // fLineCurrent: getFaultValue("F线保护电流"),
    // tfCurrent: getFaultValue("TF保护电流"),
    // impedance: getFaultValue("阻抗"),
    // impedanceAngle: getFaultValue("阻抗角"),
    // resistance: getFaultValue("电阻"),
    // reactance: getFaultValue("电抗"),
    // secondHarmonic: getFaultValue("二次谐波含量"),
    // currentSpeedStart: "-",
    // forwardCurrentSpeedStart: "-",
    // busLock: "-",
    // currentSpeedAction: "-",
    // forwardCurrentSpeedAction: "-",
    // breakerFailure: "-",
    // breakerTripCircuitFailure: "-",
    // viewReportValue: {
    //   tfCurrent: getFaultValue("TF保护电流"),
    //   impedance: getFaultValue("阻抗"),
    //   impedanceAngle: getFaultValue("阻抗角"),
    //   resistance: getFaultValue("电阻"),
    // },
    // 新增的属性
    digitalStatus,
    digitalEvent,
    sysSettingValue,
    settingValue,
    relayEnaInfo,
  };
}

/**
 * 模拟多个报告数据
 * @param xmlStr hdr 文件内容
 * @param count 数量
 */
export function mockReportListFromHdr(
  xmlStr: string,
  count: number,
  reportName: string
): ReportItem[] {
  return Array.from({ length: count }).map((_, idx) =>
    parseHdrToReportItem(xmlStr, idx + 1, reportName)
  );
}
